<?php
/**
 * Created by PhpStorm.
 * User: zhongbaitong
 * Date: 2020/1/9
 * Time: 16:52
 */

namespace app\user\home;

use app\common\controller\ApiBase;
use app\common\exception\ApiError;
use hisi\Http;

/**
 * 用户附加模块
 * Class Extra
 * @package app\user\home
 */
class Extra extends ApiBase
{
    /**
     * 解密获取 unionid（需要绑定微信开放平台）
     * @param $session_key
     * @param $encryptedData
     * @param $iv
     * @return mixed
     * @throws ApiError
     */
    public function getUnionid($session_key, $encryptedData, $iv)
    {
        //如果不是24位，就是非法
        if (strlen($session_key) != 24) {
            throw new ApiError('session_key illegal!', 0);
        }
        if (strlen($iv) != 24) {
            throw new ApiError('iv illegal!', 0);
        }

        $aesKey = base64_decode($session_key);
        $aesIV = base64_decode($iv);
        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode($result);

        if ($dataObj == NULL) {
            throw new ApiError('get union_id fail!!', 0);
        }

        if ($dataObj->watermark->appid != config('app_id')) {
            throw new ApiError('app_id mismatches!', 0);
        }

        return json_decode($dataObj, 1);
    }

    /**
     * 解密获取手机号（不支持个人小程序）
     * @return \think\response\Json
     * @throws ApiError
     */
    public function getPhone()
    {
        $input = $this->getInput('code,encryptedData,iv');
        $resp = (new Token)->getSession($input["code"]);

        $sessionKey = $resp["session_key"];
        $encryptedData = $input["encryptedData"];
        $iv = $input["iv"];

        //如果不是24位，就是非法
        if (strlen($sessionKey) != 24) {
            throw new ApiError('session_key 非法!', 0);
        }
        $aesKey = base64_decode($sessionKey);
        if (strlen($iv) != 24) {
            throw new ApiError('iv 非法!', 0);
        }
        $aesIV = base64_decode($iv);

        $aesCipher = base64_decode($encryptedData);
        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode($result, 1);
        if ($dataObj == NULL) {
            throw new ApiError('获取失败!', 0);
        }
        return $this->apiReturn($dataObj);
    }

    /**
     * 发送手机验证码（需要申请模板）
     * @return \think\response\Json
     * @throws ApiError
     */
    public function sendPhoneCode()
    {
        $input = $this->getInput("phone");
        // 手机号
        $mobile = $input["phone"];
        if (cache("phone_code:" . $mobile)) {
            return $this->apiError("请勿频发发送短信验证..");
        }

        // 随机码
        $code = random(6, 1);
        $tpl_value = ('#code#') . '=' . urldecode($code);
        $data = http_build_query([
            "mobile" => $mobile,
            "apikey" => config("yunpian.api_key"),
            "tpl_id" => config("yunpian.tpl_id"),
            "tpl_value" => $tpl_value
        ]);

        $rs = Http::post(config("yunpian.api_url"), $data);
        $rs_arr = json_decode($rs);

        if ($rs_arr->code) {
            return $this->apiError();
        }
        cache("phone_code:" . $mobile, $code, 60);
        return $this->apiReturn(compact("code"));
    }


}